package com.zhss.dfs.datanode.server;

import java.util.concurrent.CountDownLatch;

/**
 * @author: zcl
 * @date: 2021/1/27 20:20
 * @description: 负责和NameNode通讯的组件
 */
public class NameNodeServiceActor {

    /**
     * 和mater NameNode通讯的组件配置
     */
    public static final String MASTER_PROPERTIES = "MASTER_PROPERTIES";

    /**
     * 和slave NameNode通讯的组件配置
     */
    public static final String SLAVE_PROPERTIES = "SLAVE_PROPERTIES";

    /**
     * 构造器
     *
     * @param master 如果是true就加载master的配置文件
     */
    public NameNodeServiceActor(Boolean master) {
        NameNodeServiceActor serviceActor = new NameNodeServiceActor();
        if (master) {
            System.out.println("加载" + NameNodeServiceActor.MASTER_PROPERTIES);
        } else {
            System.out.println("加载" + NameNodeServiceActor.SLAVE_PROPERTIES);
        }
    }

    public NameNodeServiceActor() {
    }

    /**
     * 向NameNode注册我们这里启动的dataNode
     *
     * @param latch
     */
    public void register(CountDownLatch latch, DataNode dataNode) {
        RegisterThread registerThread = new RegisterThread(latch, dataNode);
        registerThread.start();
    }

    /**
     * 负责注册的线程
     */
    class RegisterThread extends Thread {

        //用于主线程挂起等待的锁
        CountDownLatch latch;
        //向NameNode注册的DataNode 的信息
        DataNode dataNode;

        public RegisterThread(CountDownLatch latch, DataNode dataNode) {
            this.latch = latch;
            this.dataNode = dataNode;
        }

        @Override
        public void run() {
            try {
                DataNodeInfo dataNodeInfo = dataNode;
                System.out.println("调用rpc接口去发送注册请求，将" + dataNodeInfo.toString() + "  注册到NameNode中");
                Thread.sleep(1000L);
                latch.countDown();
            } catch (Exception e) {
                System.out.println(e.toString());
            }
        }
    }

}
